package com.rr.study02.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;

import com.rr.study02.util.HibernateUtil;

public class ConexaoHibernateFilter implements Filter{
	
	private SessionFactory pSeFa;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest oSeReq, ServletResponse oSeRes,
			FilterChain oFiCh) throws IOException, ServletException {
		System.out.println("ConexaoHibernateFilter.doFilter");
		try {
			this.pSeFa.openSession().beginTransaction();
			oFiCh.doFilter(oSeReq, oSeRes);
			this.pSeFa.getCurrentSession().getTransaction().commit();
			this.pSeFa.getCurrentSession().close();
		} catch (Throwable e) {
			try {
				if(this.pSeFa.getCurrentSession().getTransaction().isActive()){
					this.pSeFa.getCurrentSession().getTransaction().rollback();
				}
			} catch (Throwable e2) {
				e2.printStackTrace();
			}
			
			throw new ServletException();
		}
	}

	@Override
	public void init(FilterConfig oFiCo) throws ServletException {
		this.pSeFa = HibernateUtil.getPSeFa();
		System.out.println("ConexaoHibernateFilter.init()");
	}

}
